<template>
  <div>
    <div class="login-wx-user login-pc-user"></div>
    <div class="is_scan_pc">
      <div class="is_bing_phone" v-show="is_bing_phone">

        <div ref="weixinLogin" class="weixinLogin WeChatQr"></div>
        <div class="text">微信扫码登录</div>
      </div>

      <div v-show="!is_bing_phone">
        <h1 class="bingphone">绑定手机号</h1>
        <el-form ref="formloginPone" :model="formloginPone" :rules="rulesPhone">
          <el-form-item prop="mobile">
            <el-input v-model="formloginPone.mobile" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item prop="code">
            <el-input class="input" style="width:63%" v-model="formloginPone.code" @keyup.enter.native="loginPhoneSubmit" placeholder="手机验证码" />
            <div class="codephone" @click="getLoginCode" v-if='isCodeShow'>{{codespan}}</div>
            <div class="codephone del" v-if='!isCodeShow'>{{codespan}}</div>
          </el-form-item>
        </el-form>
        <el-button class="userLogin" :loading="loading" type="danger" @click="loginPhoneSubmit">确定</el-button>
      </div>

    </div>
    <!-- <div v-show="!is_scan_pc" class="is_scan_pc">
            <div class="login-title">
              <span @click="bindSms(true)" :class="is_sms_password?'atv':''">短信登录</span>
              <span @click="bindSms(false)" :class="!is_sms_password?'atv':''">密码登录</span>
            </div>

            <div v-if="is_sms_password">
              <el-form ref="formloginPone" :model="formloginPone" :rules="rulesPhone">
                <el-form-item prop="mobile">
                  <el-input v-model="formloginPone.mobile" placeholder="请输入手机号" />
                </el-form-item>
                <el-form-item prop="code">
                  <el-input class="input" style="width:63%" v-model="formloginPone.code" @keyup.enter.native="loginPhoneSubmit" placeholder="手机验证码" />
                  <div class="codephone" @click="getLoginCode" v-if='isCodeShow'>{{codespan}}</div>
                  <div class="codephone del" v-if='!isCodeShow'>{{codespan}}</div>
                </el-form-item>
              </el-form>
              <el-button class="userLogin" :loading="loading" type="danger" @click="loginPhoneSubmit">登录/注册</el-button>
            </div>

            <div v-if="!is_sms_password">
              <el-form ref="formloginUser" :model="formloginUser" :rules="rulesUser">
                <el-form-item prop="username">
                  <el-input v-model="formloginUser.username" placeholder="请输入用户名" />
                </el-form-item>
                <el-form-item prop="password">
                  <el-input v-model="formloginUser.password" placeholder="请输入密码" @keyup.enter.native="loginUserSubmit" />
                </el-form-item>
              </el-form>
              <el-button class="userLogin" :loading="loading" @click="loginUserSubmit">登录</el-button>
              <div class="agreement">
                <span>登录或注册代表您已阅读并接受</span>
                <router-link to='/'>《用户协议》</router-link>

                <router-link to='/'>《隐私政策》</router-link>
              </div>
              <div class="click-register">
                没有账号？
                <span @click="userLogin()">点击注册</span>
              </div>
            </div>
          </div> -->

  </div>
  <!-- 注册 -->
  <!-- <div class="login" v-show="!is_login_register">
          <div class="close" @click="close">×</div>
          <div class="login-title-red">注册账户</div>
          <el-form ref="form" :model="formData" :rules="rules">
            <el-form-item prop="username">
              <el-input v-model="formData.username" placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="formData.password" placeholder="请输入密码" />
            </el-form-item>
            <el-form-item prop="mobile">
              <el-input v-model="formData.mobile" placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item prop="code">
              <el-input class="input" style="width:58%" v-model="formData.code" placeholder="手机验证码" />
              <div class="codephone" @click="getRegisterCode" v-if='registerisCodeShow'>{{registercodespan}}</div>
              <div class="codephone del" v-if='!registerisCodeShow'>{{registercodespan}}</div>
            </el-form-item>

          </el-form>
          <el-button class="userLogin" :loading="loading" @click="submit">注册</el-button>
          <div class="agreement">
            <span>登录或注册代表您已阅读并接受</span>
            <router-link to='/'>《用户协议》</router-link>
            <router-link to='/'>《隐私政策》</router-link>
          </div>
          <div class="click-register">
            <span @click="userLogin()">点击登录</span>
          </div>
        </div> -->

</template>

<script>
import QRCode from 'qrcodejs2'
import axios from 'axios'
export default {
  data () {
    return {
      qrUrlTime: null,
      qrUrl: 'https://api.fengwg.com/geem2/oauth2/authorize?state=',
      codUrl: 'https://api.fengwg.com/geem2/oauth2/querycode?state=',
      codUrlTime: null,
      searchInput: '',
      userInfo: '',
      time: null,
      registercodespan: '获取验证码',
      registerTime: null,
      registerisCodeShow: true,
      codespan: '获取验证码',
      isCodeShow: true,
      is_bing_phone: true, // 微信登录绑定手机
      is_login_register: true, // 登录或注册
      is_scan_pc: true, // 扫码或账号登录
      is_sms_password: true, // 短信登录或密码登录
      loading: false,
      formloginPone: {
        // 手机登录数据
        mobile: '',
        code: '',
        wxopenid: '',
        usertype: 0
      },

      formloginUser: {
        // 用户名登录数据
        username: '',
        password: ''
      },

      formData: {
        // 注册数据
        username: '',
        password: '',
        mobile: '',
        code: ''
      },
      rulesUser: {
        // 数据校验
        username: [
          {
            required: true,
            message: '请输入用户名'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码'
          },
          {
            minLength: 6,
            message: '密码长度最少 6个字符'
          }
        ]
      },
      rulesPhone: {
        // 数据校验
        mobile: [
          {
            required: true,
            message: '请输入手机号'
          },
          {
            validator: function (rule, value, callback) {
              var reg = /^1[3|4|5|6|7|8|9]\d{9}$/
              if (!reg.test(value)) {
                callback(new Error('手机号码格式不正确'))
              } else {
                callback()
              }
            }
          }
        ],

        code: [
          {
            required: true,
            message: '请输入手机验证码'
          },
          {
            minLength: 4,
            message: '密码长度最少 4 个字符'
          }
        ]
      },
      rules: {
        // 数据校验
        username: [
          {
            required: true,
            message: '请输入用户名'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码'
          },
          {
            minLength: 6,
            message: '密码长度最少6 个字符'
          }
        ],

        mobile: [
          {
            required: true,
            message: '请输入手机号'
          },
          {
            validator: function (rule, value, callback) {
              var reg = /^1[3|4|5|6|7|8|9]\d{9}$/
              if (!reg.test(value)) {
                callback(new Error('手机号码格式不正确'))
              } else {
                callback()
              }
            }
          }
        ],

        code: [
          {
            required: true,
            message: '请输入手机验证码'
          },
          {
            minLength: 4,
            message: '密码长度最少4个字符'
          }
        ]
      }
    }
  },
  watch: {},
  computed: {},
  mounted () {
    this.pollQrCode()
  },
  beforeDestroy () {
    this.close()
  },
  methods: {
    getLoginCode () {
      // 获取登录验证码

      this.$refs.formloginPone.validateField(['mobile'], valid => {
        if (!valid) {
          clearInterval(this.time)
          let numberTime = 60
          this.isCodeShow = false
          this.time = setInterval(() => {
            numberTime--
            if (numberTime <= 0) {
              numberTime = 60
              clearInterval(this.time)
              this.codespan = '获取验证码'
              this.isCodeShow = true
              return
            }
            this.codespan = numberTime + '秒后获取'
          }, 1000)

          this.$apis
            .regCaptcha({
              mobile: this.formloginPone.mobile
            })
            .then(res => {
              if (res.data.errno == 0) {
                this.$message.success('获取验证码成功')
              } else {
                this.$message.error(res.data.errmsg)
              }
            })
        }
      })
    },
    getRegisterCode () {
      // 获取注册验证码
      this.$refs.form.validateField(['mobile'], valid => {
        if (!valid) {
          clearInterval(this.registerTime)
          let numberTime = 60
          this.registerisCodeShow = false
          this.registerTime = setInterval(() => {
            numberTime--
            if (numberTime <= 0) {
              numberTime = 60
              clearInterval(this.registerTime)
              this.registercodespan = '获取验证码'
              this.registerisCodeShow = true
              return
            }
            this.registercodespan = numberTime + '秒后获取'
          }, 1000)

          this.$apis
            .regCaptcha({
              mobile: this.formData.mobile
            })
            .then(res => {
              if (res.data.errno == 0) {
                this.$message.success('获取验证码成功')
              } else {
                this.$message.error(res.data.errmsg)
              }
            })
        }
      })
    },
    submit () {
      // 注册
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          this.$apis
            .register({
              code: this.formData.code,
              mobile: this.formData.mobile,
              password: this.formData.password,
              username: this.formData.username
            })
            .then(res => {
              this.loading = false
              if (res.data.errno == 0) {
                this.$message.success('注册成功')
                this.userInfo = res.data
                this.init(res.data.data)
              } else {
                this.$message.error(res.data.errmsg)
              }
            })
        }
      })
    },

    randomString (len) {
      let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789'
      let maxPos = chars.length
      let character = ''
      for (let i = 0; i < len; i++) {
        character += chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return character + new Date().getTime()
    },

    creatQrCode (url) {
      var element = this.$refs.weixinLogin
      element.innerHTML = ''
      var qrcode = new QRCode(element, {
        text: url, // 需要转换为二维码的内容
        width: 300,
        height: 300,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H
      })
    },
    pollQrCode () {
      var cod = this.randomString(6)
      clearTimeout(this.qrUrlTime)
      clearInterval(this.codUrlTime)
      this.creatQrCode(this.qrUrl + cod)
      let self = this
      this.qrUrlTime = setTimeout(function () {
        self.pollQrCode()
      }, 1000 * 60)
      this.codUrlTime = setInterval(function () {
        axios.get(self.codUrl + cod + '&timestamp=' + Date.now()).then(res => {
          if (res.data.data.code != '') {
            clearTimeout(self.qrUrlTime)
            clearInterval(self.codUrlTime)
            self.loginByScanWeixin(res.data.data.code)
          }
        })
      }, 1000)
    },
    loginByScanWeixin (e) {
      // 微信扫码登录
      this.$apis
        .loginByScanWeixin({
          code: e
        })
        .then(res => {
          if (res.data.errno == 0) {
            const data = res.data.data
            if (data.token) {
              this.$message.success('登录成功')
              this.userInfo = data
              this.init(data)
            } else {
              this.formloginPone.wxopenid = data.openId
              this.is_bing_phone = false
            }
          } else {
            this.$message.error(res.data.errmsg)
          }
        })
    },
    loginPhoneSubmit () {
      // 手机登录
      this.$refs.formloginPone.validate(valid => {
        if (valid) {
          this.loading = true
          this.$apis.loginbymobile(this.formloginPone).then(res => {
            this.loading = false
            if (res.data.errno == 0) {
              this.$message.success('登录成功')
              this.userInfo = res.data.data
              this.init(res.data.data)
            } else {
              this.$message.error(res.data.errmsg)
            }
          })
        }
      })
    },
    loginUserSubmit () {
      // 用户名登录

      this.$refs.formloginUser.validate(valid => {
        if (valid) {
          this.loading = true
          this.$apis
            .login({
              password: this.formloginUser.password,
              username: this.formloginUser.username,
              usertype: 0
            })
            .then(res => {
              this.loading = false
              if (res.data.errno == 0) {
                this.$message.success('登录成功')
                this.userInfo = res.data.data
                this.init(res.data.data)
              } else {
                this.$message.error(res.data.errmsg)
              }
            })
        }
      })
    },

    close () {
      this.is_scan_pc = true
      this.is_bing_phone = true
      this.formloginPone.wxopenid = ''
      this.formloginPone.mobile = ''
      this.formloginPone.code = ''
      this.formloginUser.username = ''
      this.formloginUser.password = ''
      this.formData.username = ''
      this.formData.password = ''
      this.formData.mobile = ''
      this.formData.code = ''
      clearTimeout(this.qrUrlTime)
      clearInterval(this.codUrlTime)
    },
    init (e) {
      this.close()
      localStorage.setItem('token', e.token)
      this.$store.commit('setUserInfo', e)
      localStorage.setItem('storage_key', JSON.stringify(e))
      this.$router.push({ path: '../my' })
    },
    userLogin () {
      this.is_login_register = !this.is_login_register
      this.$refs.form.clearValidate()
    },
    BindLoginUser () {
      if (this.is_scan_pc) {
        this.is_scan_pc = false
        clearTimeout(this.qrUrlTime)
        clearInterval(this.codUrlTime)
      } else {
        this.pollQrCode()
        this.is_scan_pc = true
      }
    },
    bindSms (e) {
      if (this.is_sms_password == e) {
        return
      }
      if (e) {
        this.$refs.formloginUser.clearValidate()
      } else {
        this.$refs.formloginPone.clearValidate()
      }

      this.is_sms_password = e
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.el-dialog__header {
  padding: 0px;
}
/deep/ .el-dialog__body {
  padding: 0px 20px;
}
.content {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}
.logo {
  //   display: flex;
  //   flex-direction: row;
  //   align-items: center;
  //   flex: 1;
}

.logo img {
  max-height: 46px;
  width: 160px;
}

.logo span {
  margin-left: 16px;
}

.uni-input {
  width: 437px;
  height: 40px;
  box-sizing: border-box;
  background: #f3f4f5;
  border: 1px solid #f3f4f5;
  border-radius: 22px;
  padding: 0px 20px;
}

.forget-password {
  span-align: right;
  color: #3377aa;
  cursor: pointer;
}
.forget-password:hover {
  color: #da2740;
}
.userLogin {
  background: #da2740;
  color: #fff;
  margin: 15px 0;
  width: 100%;
}
uni-navigator {
  display: inline;
  color: #3377aa;
}
.click-register {
  text-align: right;
  margin: 25px 0 10px;
  span {
    color: #3377aa;
    cursor: pointer;
  }
}

.is_bing_phone {
  text-align: center;
  overflow: hidden;
  .text {
    font-size: 22px;
  }
  .WeChatQr {
    padding: 20px 0px;
    display: flex;
    justify-content: center;
    margin-top: 50px;
  }
}
.is_scan_pc {
  overflow: hidden;
  width: 400px;
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  margin: auto;
  height: 500px;
}
</style>
